'use client';

import { useState, useEffect } from 'react';
import Modal from 'react-modal';
import RichTextEditor from '../components/RichTextEditor'; 
import Image from 'next/image';
import { myLoader } from '../utils/api';

// 定义样式选项类型
type StyleOption = {
  id: number;
  name: string;
  category: string;
  icon?: string;    // 可选的图标URL
  description?: string;  // 可选的描述文本
  ai_parsed_text: string;
  image?: string;
  collectionId: string;
  collectionName: string;
};

type CategoryType = {
  title: string;
  key: string;  // 用于API请求的唯一标识
  options: StyleOption[];
  total: number;  // 该分类的总数量
  icon: string;
  collectionId: string;
  description: string;
};


interface ItemType {
  name: string;
  id: string;
  collectionId: string;
  collectionName: string;
  icon: string;
  description: string;
}

// 每页显示6个元素
const ITEMS_PER_PAGE = 6;


export default function StyleSelector() {
  const [categories, setCategories] = useState<CategoryType[]>([]);
  const [selectedTexts, setSelectedTexts] = useState<string[]>([]);
  const [categoryPages, setCategoryPages] = useState<Record<string, number>>({});
  const [loading, setLoading] = useState<Record<string, boolean>>({});
  const [modalIsOpen, setModalIsOpen] = useState(false);
  const [modalText, setModalText] = useState('');
  const [tooltipText, setTooltipText] = useState<string | null>(null);
  const [tooltipPosition, setTooltipPosition] = useState<{ top: number; left: number } | null>(null);
  const [copySuccess, setCopySuccess] = useState(false);

  // 获取分类数据
  const fetchCategoryOptions = async (categoryKey: string, page: number) => {
    setLoading(prev => ({ ...prev, [categoryKey]: true }));
    try {
      const filter = encodeURIComponent(`(tatoo_categoty_name.id='${categoryKey}' && is_show=true)`);
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/collections/tatoo_elements/records?expand=tatoo_categoty_name&filter=${filter}&page=${page}&perPage=${ITEMS_PER_PAGE}`
      );
      const data = await response.json();
      
      const items = data.items || [];
      const totalItems = items.length;

      // 如果数据不足6个，补足到6个
      const placeholders = Array.from({ length: Math.max(0, 6 - totalItems) }, (_, index) => ({
        id: `placeholder-${index}`,
        name: '暂无样式',
        image: '', // 可以设置一个默认的占位图
        ai_parsed_text: '暂无描述',
      }));

      setCategories(prev => prev.map(category => 
        category.key === categoryKey 
          ? { ...category, options: [...items, ...placeholders], total: data.totalItems }
          : category
      ));
    } catch (error) {
      console.error('获取样式选项失败:', error);
    } finally {
      setLoading(prev => ({ ...prev, [categoryKey]: false }));
    }
  };

  const handlePageChange = async (categoryKey: string, direction: 'prev' | 'next') => {
    // 确保当前页码存在，如果不存在则初始化为1
    const currentPage = categoryPages[categoryKey] || 1;
    const newPage = direction === 'prev' 
        ? Math.max(1, currentPage - 1)
        : currentPage + 1;

    setCategoryPages(prev => ({
        ...prev,
        [categoryKey]: newPage
    }));

    await fetchCategoryOptions(categoryKey, newPage);
  };

  // 初始加载
  useEffect(() => {
    const fetchInitialCategories = async () => {
      try {
        const response = await fetch(`${process.env.NEXT_PUBLIC_API_ENDPOINT}/api/collections/tatoo_category/records`);
        const data = await response.json();
        

        const categories: CategoryType[] = data.items.map((item: ItemType) => ({
          title: item.name,
          key: item.id,
          collectionId: item.collectionId,
          collectionName: item.collectionName,
          icon: item.icon,
          options: [],
          description: item.description,
          total: data.totalItems,
        }));

        setCategories(categories);
        categories.forEach(category => {
          fetchCategoryOptions(category.key, 1);
        });
      } catch (error) {
        console.error('加载分类数据失败:', error);
      }
    };

    fetchInitialCategories();
  }, []);

  const handleStyleSelect = (id: number, aiParsedText: string) => {
    setSelectedTexts(prev => 
      prev.includes(aiParsedText) 
        ? prev.filter(item => item !== aiParsedText)
        : [...prev, aiParsedText]
    );
  };

  const handleSubmit = async () => {
    if (!selectedTexts.length) {
        return;
    }
    const combinedText = selectedTexts.join('\n');
    setModalText(combinedText);
    setModalIsOpen(true);
  };

  const handleCopy = () => {
    // 创建一个临时的textarea元素
    const textarea = document.createElement('textarea');
    textarea.value = modalText;
    textarea.style.position = 'fixed';  // 防止页面滚动
    textarea.style.opacity = '0';      // 隐藏元素
    
    // 添加到DOM中
    document.body.appendChild(textarea);
    
    // 选择并复制文本
    textarea.select();
    try {
      const successful = document.execCommand('copy');
      if (successful) {
        setCopySuccess(true);
      } else {
        alert('复制失败，请手动复制文本');
      }
    } catch (err) {
      console.error('复制失败:', err);
      alert('复制失败，请手动复制文本');
    }
    
    // 移除临时元素
    document.body.removeChild(textarea);
  };
  

  const handleLongPress = (text: string, event: React.TouchEvent) => {
    setTooltipText(text);
    const { clientX, clientY } = event.touches[0];
    setTooltipPosition({ top: clientY, left: clientX });
  };

  const handleTouchEnd = () => {
    setTooltipText(null);
    setTooltipPosition(null);
  };

  const closeModal = () => {
    setModalIsOpen(false);
  };

  return (
    <div className="flex flex-col h-full">
      <h2 className="text-xl font-bold mb-4 text-gray-800 dark:text-gray-100">选择样式</h2>
      
      <div className="flex-1 overflow-y-auto space-y-6">
        {categories.map((category) => {
          const currentPage = categoryPages[category.key];
          const maxPage = Math.ceil(category.total / ITEMS_PER_PAGE);
          
          return (
            <div key={category.key} className="space-y-3">
              <div className="flex items-center space-x-2">
                {/* 分类的图标 */}
                {category.icon && (
                  <div className="w-6 h-6 rounded-full overflow-hidden">
                    <Image
                      loader={myLoader}
                      src={`${category.collectionId}/${category.key}/${category.icon}`}
                      alt={category.title}
                      className="w-full h-full object-cover"
                      width={500} height={300}
                    />
                  </div>
                )}
                <h3 className="text-md font-medium text-gray-600 dark:text-gray-300 pl-1" title={category.description}>
                  {category.title}
                </h3>
              </div>
            
              {/* 选项网格容器 */}
              <div className="relative group">
                {/* 左侧分页按钮 */}
                <button
                  onClick={() => handlePageChange(category.key, 'prev')}
                  disabled={currentPage === 1 || loading[category.key]}
                  className={`absolute left-0 top-1/2 -translate-y-1/2 -translate-x-2 z-10
                    w-8 h-8 flex items-center justify-center
                    rounded-full border-2 text-sm shadow-md
                    group-hover:scale-110 transition-all duration-200
                    ${(currentPage === 1 || loading[category.key])
                      ? 'opacity-50 cursor-not-allowed border-gray-200 text-gray-400 bg-white/80'
                      : 'border-pink-300 text-pink-500 bg-white hover:bg-pink-50 hover:border-pink-400 hover:text-pink-600 hover:shadow-lg dark:bg-gray-800 dark:hover:bg-gray-700 dark:border-pink-500 dark:text-pink-400'
                    }
                  `}
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M15 19l-7-7 7-7" />
                  </svg>
                </button>

                {/* 选项网格 */}
                <div className="grid grid-cols-6 gap-2 px-8">
                  {loading[category.key] ? (
                    // 加载状态占位
                    Array.from({ length: ITEMS_PER_PAGE }).map((_, index) => (
                      <div 
                        key={index}
                        className="aspect-square animate-pulse bg-pink-50 dark:bg-gray-800 
                          rounded-lg shadow-sm"
                      />
                    ))
                  ) : (
                    category.options.map((option) => (
                      <button
                        key={option.id}
                        onClick={() => {
                          // 仅在选项不是占位符时才允许选择
                          if (!option.name.includes('暂无样式')) {
                            handleStyleSelect(option.id, option.ai_parsed_text);
                          }
                        }}
                        onTouchStart={(event) => handleLongPress(option.ai_parsed_text, event)}
                        onTouchEnd={handleTouchEnd}
                        className={`
                          aspect-square rounded-lg transition-all duration-200
                          flex flex-col items-center justify-center gap-1 p-2
                          text-xs font-medium
                          ${selectedTexts.includes(option.ai_parsed_text)
                            ? 'bg-pink-50 border-2 border-pink-400 text-pink-600 shadow-inner dark:bg-pink-900 dark:border-pink-500 dark:text-pink-300'
                            : 'bg-white border border-gray-100 text-gray-600 hover:border-pink-200 hover:bg-pink-50/50 hover:shadow-sm dark:bg-gray-800 dark:border-gray-700 dark:text-gray-300 dark:hover:border-pink-800 dark:hover:bg-pink-900/30'
                          }
                        `}
                        title={option.ai_parsed_text}
                      >
                        {option.image ? (
                          <Image
                            loader={myLoader}
                            src={`${option.collectionId}/${option.id}/${option.image}`}
                            alt={option.name}
                            className="w-full h-full object-contain"
                            width={500} height={300}
                          />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center bg-gray-200">
                            <span>{option.name}</span>
                          </div>
                        )}
                        <span className="line-clamp-2 text-center">
                          {option.name}
                        </span>
                      </button>
                    ))
                  )}
                </div>

                {/* 右侧分页按钮 */}
                <button
                  onClick={() => handlePageChange(category.key, 'next')}
                  disabled={currentPage === maxPage || loading[category.key]}
                  className={`absolute right-0 top-1/2 -translate-y-1/2 translate-x-2 z-10
                    w-8 h-8 flex items-center justify-center
                    rounded-full border-2 text-sm shadow-md
                    group-hover:scale-110 transition-all duration-200
                    ${(currentPage === maxPage || loading[category.key])
                      ? 'opacity-50 cursor-not-allowed border-gray-200 text-gray-400 bg-white/80'
                      : 'border-pink-300 text-pink-500 bg-white hover:bg-pink-50 hover:border-pink-400 hover:text-pink-600 hover:shadow-lg dark:bg-gray-800 dark:hover:bg-gray-700 dark:border-pink-500 dark:text-pink-400'
                    }
                  `}
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* 工具提示 */}
      {tooltipText && tooltipPosition && (
        <div
          className="absolute bg-gray-800 text-white text-xs rounded p-1"
          style={{
            top: tooltipPosition.top + 10, // 调整位置
            left: tooltipPosition.left,
            transform: 'translate(-50%, 0)',
          }}
        >
          {tooltipText}
        </div>
      )}

      {/* 模态框 */}
      <Modal
        isOpen={modalIsOpen}
        onRequestClose={closeModal}
        contentLabel="AI Parsed Text"
        className="modal"
        overlayClassName="overlay"
      >
        <div className="fixed inset-0 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-lg p-4">
            <h2 className="text-lg font-bold">描述</h2>
            <RichTextEditor 
                initialContent={modalText} 
                onChange={(content) => setModalText(content)} // Update modal text on change
            />
            <button onClick={closeModal} className="mt-4 bg-blue-500 text-white rounded px-4 py-2">
                关闭
            </button>
            <button 
                onClick={handleCopy}
                className="mt-2 bg-green-500 text-white rounded px-4 py-2"
            >
                复制
            </button>
            {copySuccess && (
                <div className="mt-2 text-green-500">文本已复制到剪贴板！</div>
            )}
          </div>
        </div>
      </Modal>

      {/* 生成按钮 - 更柔和的样式 */}
      <button
        onClick={handleSubmit}
        className="mt-6 w-full py-3 bg-gradient-to-r from-pink-500 to-rose-500 
          text-white rounded-lg hover:from-pink-600 hover:to-rose-600 
          transition-all duration-300 shadow-md hover:shadow-lg
          dark:from-pink-600 dark:to-rose-600 dark:hover:from-pink-700 dark:hover:to-rose-700"
      >
        聚合提示词
      </button>
    </div>
  );
} 